<!-- page -->
<form class="form-horizontal pt-15 form-validate widthFixedForm">
    <div class="form-group">
        <label class="col-md-2 control-label">模板名称</label>
        <div class="col-md-5"><input class="form-control" id="template_name" name="template_name" required></div>
    </div>
    <div class="form-group">
        <label class="col-md-2 control-label">单据尺寸</label>
        <div class="col-md-5">
            <div class="input-group">
                <input type="number" id="input_width" name="width"
                       class="form-control number-form-control documentsWidth" min="0"
                       value="250" placeholder="宽度" required>
                <div class="input-group-addon"> mm ×</div>
                <input type="number" id="input_height" name="height"
                       class="form-control number-form-control documentsHeight" min="0"
                       value="150" placeholder="高度" required>
                <div class="input-group-addon">mm</div>
            </div>
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-2 control-label">参照底图</label>
        <div class="col-md-5">
            <div class="input-group">
                <input type="text" class="form-control reproduction" name="" id="input_bg" value="" disabled="">
                <span class="input-group-btn">
                        <a href="javascript:void(0);" id="" class="btn btn-primary mr-04"
                           data-toggle="editExpressPicture">选择图片</a>
                        <a href="javascript:void(0);" class="btn btn-primary clearPic">清除图片</a>
                </span>
            </div>
        </div>
    </div>

    <div class="panel" style="height: auto; overflow: hidden; background: none;">
        <div class="edit-left">
            <div class="panel panel-default">
                <div class="panel-heading clearfix">
                    <span class="pull-left" style="margin-top:6px"><i class="icon icon-edit"></i> 元素编辑器</span>
                    <div class="pull-right">
                        <a class="btn btn-danger mr-04 fs-12 deleteinput" style="display: none"> <i
                                class="icon icon-delete"></i> 删除打印项</a>
                        <a class="btn btn-primary mr-04 fs-12 editContent"> <i class="icon icon-add1"></i> 编辑内容框</a>
                    </div>


                </div>
                <div class="panel-body">
                    <p class="item-tip">请先选中您要编辑的内容框</p>
                    <div class="items" style="display: none;">
                        <div class="form-group cate1">
                            <label class="col-sm-2 control-label">买家信息</label>
                            <div class="col-sm-10">
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="consignee_name" title="收货人"> 收货人</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="consignee_mobile" title="收货人电话"> 收货人电话</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="consignee_province" title="收货人省份"> 收货人省份</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="consignee_city" title="收货人城市"> 收货人城市</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="consignee_district" title="收货人区域"> 收货人区域</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="consignee_address" title="收货人详细地址"> 收货人详细地址</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="consignee_nick_name" title="收货人昵称"> 收货人昵称</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="consignee_zip_code" title="收货人邮编"> 收货人邮编</label>
                            </div>
                        </div>
                        <div class="form-group cate1">
                            <label class="col-sm-2 control-label">卖家信息</label>
                            <div class="col-sm-10">
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="sender_name" title="发货人"> 发货人</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="sender_mobile" title="发货人电话"> 发货人电话</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="sender_province" title="发货人省份"> 发货人省份</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="sender_city" title="发货人城市"> 发货人城市</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="sender_district" title="发货人区域"> 发货人区域</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="sender_address" title="发货人详细地址"> 发货人详细地址</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="sender_sign" title="发货人签名"> 发货人签名</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="mall_name" title="商城名称"> 商城名称</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="delivery_date" title="发货日期"> 发货日期</label>
                                <label class="checkbox-inline">
                                    <input type="checkbox" value="goods_detail" title="商品明细"> 商品明细</label>
                            </div>
                        </div>

                        <div class="form-group">
                            <div class="col-sm-12 fs-12">
                                <div class="input-group">
                                    <div class="input-group-addon">字体</div>
                                    <select class="form-control" id="item-font" style="min-width:68px">
                                        <option value="微软雅黑">微软雅黑</option>
                                        <option value="黑体">黑体</option>
                                        <option value="宋体">宋体</option>
                                        <option value="新宋体">新宋体</option>
                                        <option value="幼圆">幼圆</option>
                                        <option value="华文细黑">华文细黑</option>
                                        <option value="隶书">隶书</option>
                                        <option value="Arial">Arial</option>
                                        <option value="Arial Narrow">Arial Narrow</option>
                                    </select>

                                    <div class="input-group-addon">字号</div>
                                    <select class="form-control" id="item-size" style="min-width:68px">
                                        <option value="8">8</option>
                                        <option value="10">10</option>
                                        <option value="12">12</option>
                                        <option value="14">14</option>
                                    </select>

                                    <div class="input-group-addon">对齐</div>
                                    <select class="form-control" id="item-align" style="min-width:76px">
                                        <option value="left">居左</option>
                                        <option value="center">居中</option>
                                        <option value="right">居右</option>
                                    </select>

                                    <div class="input-group-addon">加粗</div>
                                    <select class="form-control" id="item-bold" style="min-width:76px">
                                        <option value="">不加粗</option>
                                        <option value="bold">加粗</option>
                                    </select>

                                    <div class="input-group-addon">前文字</div>
                                    <input type="text" id="item-pre" class="form-control">
                                    <div class="input-group-addon">后文字</div>
                                    <input type="text" id="item-last" class="form-control">

                                    <div class="input-group-addon" id="item-color">颜色</div>
                                    <!--<input type="color"  name="" class="colorpicker" value="#ffffff">-->
                                    <input type="hidden" class="form-control" name="color" value="" id="color2">
                                    <span class="input-group-addon" style="width:35px;border-left:none;"></span>
                                    <span class="input-group-btn">
                                         <button class="btn btn-default colorpicker" type="button">选择颜色 ▼</button>
                                    </span>
                                    <!--<input type="color"  name="" class="colorpicker" value="#ffffff">-->

                                </div>
                            </div>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <div class="edit-right">
            <div id="container" class="eaitExpressContainer" style="background-size:100% 100%; height: 150mm;">
            </div>
        </div>
    </div>

    <div class="form-group">
        <label class="col-md-2 control-label"></label>
        <div class="col-md-8">
            <button class="btn btn-primary J-save" type="submit">保存</button>
            <a href="javascript:history.go(-1);" class="btn btn-default">返回</a>
        </div>
    </div>


</form>

<!-- page end -->
<script id="tpl_drag" type="text/html">
    <%each items as item index%>
    <div class="drag" cate="<%item.cate%>" index="<%item.index%>" style="<%item.style%>" fields="<%item.fields%>"
         item-size="<%item.item_size%>" item-font="<%item.item_font%>" items="<%item.items%>"
         item-align="<%item.item_align%>" item-color="<%item.item_color%>" item-pre="<%item.item_pre%>"
         item-last="<%item.item_last%>" item-string="<%item.item_string%>">
        <div class="text"
             style="font-size: <%item.item_size%>pt;
              color: <%item.item_color%>;
              text-align: <%item.item_align%>;
              font-family: <%item.item_font%>;">
            <%item.item_pre + item.item_string + item.item_last%>
        </div>
        <div class="rRightDown"></div>
        <div class="rLeftDown"></div>
        <div class="rRightUp"></div>
        <div class="rLeftUp"></div>
        <div class="rRight"></div>
        <div class="rLeft"></div>
        <div class="rUp"></div>
        <div class="rDown"></div>
    </div>
    <%/each%>
</script>
<script>
    require(['contextmenu', 'tpl', 'utilAdmin'], function (contextmenu, tpl,utilAdmin) {
        // demo
        var isIE = document.all ? true : false;
        var Class = {
            create: function () {
                return function () {
                    this.initialize.apply(this, arguments);
                };
            }
        };
        var CurrentStyle = function (element) {
            return (
                element.currentStyle || document.defaultView.getComputedStyle(element, null)
            );
        };
        var BindAsEventListener = function (object, fun) {
            var args = Array.prototype.slice.call(arguments).slice(2);
            return function (event) {
                return fun.apply(object, [event || window.event].concat(args));
            };
        };
        var Bind = function (object, fun) {
            return function () {
                return fun.apply(object, arguments);
            };
        };
        var Extend = function (destination, source) {
            for (var property in source) {
                destination[property] = source[property];
            }
        };

        function addEventHandler(oTarget, sEventType, fnHandler) {
            if (oTarget.addEventListener) {
                oTarget.addEventListener(sEventType, fnHandler, false);
            } else if (oTarget.attachEvent) {
                oTarget.attachEvent("on" + sEventType, fnHandler);
            } else {
                oTarget["on" + sEventType] = fnHandler;
            }
        }

        function removeEventHandler(oTarget, sEventType, fnHandler) {
            if (oTarget.removeEventListener) {
                oTarget.removeEventListener(sEventType, fnHandler, false);
            } else if (oTarget.detachEvent) {
                oTarget.detachEvent("on" + sEventType, fnHandler);
            } else {
                oTarget["on" + sEventType] = null;
            }
        }

        function setCurrentDrag(obj) {
            currentDrag = obj;
            var cate = obj.attr('cate');
            bindItems();
            $(".item-tip").hide();
            $('.items').show();
            $(".deleteinput").show();
            if (cate == 1) {
                $(".cate1").show();
                $(".cate2").hide();
            }
            if (cate == 2) {
                $(".cate2").show();
                $(".cate1").hide();
            }
            $('.drag').css('border', '1px solid #aaa');
            obj.css('border', '1px solid #428bca');
        }

        function bindItems() {
            var items = currentDrag.attr('items') || "";
            var values = items.split(',');
            $('.items').find(':checkbox').each(function () {
                $(this).get(0).checked = false;
            });
            $('#item-font').val('');
            $('#item-size').val('');
            $('#item-bold').val('');
            for (var i in values) {
                if (values[i] != '') {
                    $('.items').find(":checkbox[value='" + values[i] + "']").get(0).checked = true;
                }
            }
            $('#item-font').val(currentDrag.attr('item-font') || '');
            $('#item-size').val(currentDrag.attr('item-size') || '');
            $('#item-bold').val(currentDrag.attr('item-bold') || '');
            $('#item-pre').val(currentDrag.attr('item-pre') || '');
            $('#item-last').val(currentDrag.attr('item-last') || '');
            $('#item-align').val(currentDrag.attr('item-align') || '');

            var itemcolor = $('#item-color');
            var input = $('#color2');
            // var picker = itemcolor.find('.sp-preview-inner');
            var color = currentDrag.attr('item-color') || '#000';
            // console.log(currentDrag.attr('item-color'));
            // console.log(color);
            input.val(color);
            var aa = input.val();
            // console.log(123);
            // console.log(aa);
            // picker.css({
            //     'background-color': color
            // });
            var timer = 0;
            timer = setInterval(function () {
                var cate = currentDrag.attr("cate");
                if (cate == 1) {
                    currentDrag.attr('item-color', input.val()).find('.text').css('color', input.val());
                }
                if (cate == 2) {
                    currentDrag.attr('item-color', input.val()).find('.text-table').css('color', input.val());
                }
                currentDrag.attr('item-pre', $('#item-pre').val());
                currentDrag.attr('item-last', $('#item-last').val());
                var pre = currentDrag.attr('item-pre') || "";
                var last = currentDrag.attr('item-last') || "";
                var string = currentDrag.attr('item-string') || "";
                currentDrag.find('.text').html(pre + string + last);
            }, 10);
        }

//缩放程序
        var Resize = Class.create();
        Resize.prototype = {
            //缩放对象
            initialize: function (obj, options) {
                this._obj = obj.get(0); //缩放对象

                this._styleWidth = this._styleHeight = this._styleLeft = this._styleTop = 0; //样式参数
                this._sideRight = this._sideDown = this._sideLeft = this._sideUp = 0; //坐标参数
                this._fixLeft = this._fixTop = 0; //定位参数
                this._scaleLeft = this._scaleTop = 0; //定位坐标

                this._mxSet = function () {
                }; //范围设置程序
                this._mxRightWidth = this._mxDownHeight = this._mxUpHeight = this._mxLeftWidth = 0; //范围参数
                this._mxScaleWidth = this._mxScaleHeight = 0; //比例范围参数

                this._fun = function () {
                }; //缩放执行程序

                //获取边框宽度
                var _style = CurrentStyle(this._obj);
                this._borderX =
                    (parseInt(_style.borderLeftWidth) || 0) +
                    (parseInt(_style.borderRightWidth) || 0);
                this._borderY =
                    (parseInt(_style.borderTopWidth) || 0) +
                    (parseInt(_style.borderBottomWidth) || 0);
                //事件对象(用于绑定移除事件)
                this._fR = BindAsEventListener(this, this.Resize);
                this._fS = Bind(this, this.Stop);

                this.SetOptions(options);
                //范围限制
                this.Max = !!this.options.Max;
                this._mxContainer = $(this.options.mxContainer).get(0) || null;
                this.mxLeft = Math.round(this.options.mxLeft);
                this.mxRight = Math.round(this.options.mxRight);
                this.mxTop = Math.round(this.options.mxTop);
                this.mxBottom = Math.round(this.options.mxBottom);
                //宽高限制
                this.Min = !!this.options.Min;
                this.minWidth = Math.round(this.options.minWidth);
                this.minHeight = Math.round(this.options.minHeight);
                //按比例缩放
                this.Scale = !!this.options.Scale;
                this.Ratio = Math.max(this.options.Ratio, 0);

                this.onResize = this.options.onResize;

                this._obj.style.position = "absolute";
                !this._mxContainer ||
                CurrentStyle(this._mxContainer).position == "relative" ||
                (this._mxContainer.style.position = "relative");
            },
            //设置默认属性
            SetOptions: function (options) {
                this.options = {
                    //默认值
                    Max: false, //是否设置范围限制(为true时下面mx参数有用)
                    mxContainer: "", //指定限制在容器内
                    mxLeft: 0, //左边限制
                    mxRight: 9999, //右边限制
                    mxTop: 0, //上边限制
                    mxBottom: 9999, //下边限制
                    Min: false, //是否最小宽高限制(为true时下面min参数有用)
                    minWidth: 50, //最小宽度
                    minHeight: 50, //最小高度
                    Scale: false, //是否按比例缩放
                    Ratio: 0, //缩放比例(宽/高)
                    onResize: function () {
                    } //缩放时执行
                };
                Extend(this.options, options || {});
            },
            //设置触发对象
            Set: function (resize, side) {
                var fun;
                if (!resize) return;
                //根据方向设置
                switch (side.toLowerCase()) {
                    case "up":
                        fun = this.Up;
                        break;
                    case "down":
                        fun = this.Down;
                        break;
                    case "left":
                        fun = this.Left;
                        break;
                    case "right":
                        fun = this.Right;
                        break;
                    case "left-up":
                        fun = this.LeftUp;
                        break;
                    case "right-up":
                        fun = this.RightUp;
                        break;
                    case "left-down":
                        fun = this.LeftDown;
                        break;
                    case "right-down":
                    default:
                        fun = this.RightDown;
                }
                //设置触发对象
                addEventHandler(
                    resize.get(0),
                    "mousedown",
                    BindAsEventListener(this, this.Start, fun)
                );
            },
            //准备缩放
            Start: function (e, fun, touch) {
                //防止冒泡(跟拖放配合时设置)
                e.stopPropagation ? e.stopPropagation() : (e.cancelBubble = true);
                //设置执行程序
                this._fun = fun;
                //样式参数值
                this._styleWidth = this._obj.clientWidth;
                this._styleHeight = this._obj.clientHeight;
                this._styleLeft = this._obj.offsetLeft;
                this._styleTop = this._obj.offsetTop;
                //四条边定位坐标
                this._sideLeft = e.clientX - this._styleWidth;
                this._sideRight = e.clientX + this._styleWidth;
                this._sideUp = e.clientY - this._styleHeight;
                this._sideDown = e.clientY + this._styleHeight;
                //top和left定位参数
                this._fixLeft = this._styleLeft + this._styleWidth;
                this._fixTop = this._styleTop + this._styleHeight;
                //缩放比例
                if (this.Scale) {
                    //设置比例
                    this.Ratio =
                        Math.max(this.Ratio, 0) || this._styleWidth / this._styleHeight;
                    //left和top的定位坐标
                    this._scaleLeft = this._styleLeft + this._styleWidth / 2;
                    this._scaleTop = this._styleTop + this._styleHeight / 2;
                }
                //范围限制
                if (this.Max) {
                    //设置范围参数
                    var mxLeft = this.mxLeft,
                        mxRight = this.mxRight,
                        mxTop = this.mxTop,
                        mxBottom = this.mxBottom;
                    //如果设置了容器，再修正范围参数
                    if (!!this._mxContainer) {
                        mxLeft = Math.max(mxLeft, 0);
                        mxTop = Math.max(mxTop, 0);
                        mxRight = Math.min(mxRight, this._mxContainer.clientWidth);
                        mxBottom = Math.min(mxBottom, this._mxContainer.clientHeight);
                    }
                    //根据最小值再修正
                    mxRight = Math.max(
                        mxRight,
                        mxLeft + (this.Min ? this.minWidth : 0) + this._borderX
                    );
                    mxBottom = Math.max(
                        mxBottom,
                        mxTop + (this.Min ? this.minHeight : 0) + this._borderY
                    );
                    //由于转向时要重新设置所以写成function形式
                    this._mxSet = function () {
                        this._mxRightWidth = mxRight - this._styleLeft - this._borderX;
                        this._mxDownHeight = mxBottom - this._styleTop - this._borderY;
                        this._mxUpHeight = Math.max(
                            this._fixTop - mxTop,
                            this.Min ? this.minHeight : 0
                        );
                        this._mxLeftWidth = Math.max(
                            this._fixLeft - mxLeft,
                            this.Min ? this.minWidth : 0
                        );
                    };
                    this._mxSet();
                    //有缩放比例下的范围限制
                    if (this.Scale) {
                        this._mxScaleWidth =
                            Math.min(
                                this._scaleLeft - mxLeft,
                                mxRight - this._scaleLeft - this._borderX
                            ) * 2;
                        this._mxScaleHeight =
                            Math.min(
                                this._scaleTop - mxTop,
                                mxBottom - this._scaleTop - this._borderY
                            ) * 2;
                    }
                }
                //mousemove时缩放 mouseup时停止
                addEventHandler(document, "mousemove", this._fR);
                addEventHandler(document, "mouseup", this._fS);
                if (isIE) {
                    addEventHandler(this._obj, "losecapture", this._fS);
                    this._obj.setCapture();
                } else {
                    addEventHandler(window, "blur", this._fS);
                    e.preventDefault();
                }
            },
            //缩放
            Resize: function (e) {
                //清除选择
                window.getSelection
                    ? window.getSelection().removeAllRanges()
                    : document.selection.empty();
                //执行缩放程序
                this._fun(e);
                //设置样式，变量必须大于等于0否则ie出错
                with (this._obj.style) {
                    width = this._styleWidth + "px";
                    height = this._styleHeight + "px";
                    top = this._styleTop + "px";
                    left = this._styleLeft + "px";
                }
                //附加程序
                this.onResize();
            },
            //缩放程序
            //上
            Up: function (e) {
                this.RepairY(this._sideDown - e.clientY, this._mxUpHeight);
                this.RepairTop();
                this.TurnDown(this.Down);
            },
            //下
            Down: function (e) {
                this.RepairY(e.clientY - this._sideUp, this._mxDownHeight);
                this.TurnUp(this.Up);
            },
            //右
            Right: function (e) {
                this.RepairX(e.clientX - this._sideLeft, this._mxRightWidth);
                this.TurnLeft(this.Left);
            },
            //左
            Left: function (e) {
                this.RepairX(this._sideRight - e.clientX, this._mxLeftWidth);
                this.RepairLeft();
                this.TurnRight(this.Right);
            },
            //右下
            RightDown: function (e) {
                this.RepairAngle(
                    e.clientX - this._sideLeft,
                    this._mxRightWidth,
                    e.clientY - this._sideUp,
                    this._mxDownHeight
                );
                this.TurnLeft(this.LeftDown) || this.Scale || this.TurnUp(this.RightUp);
            },
            //右上
            RightUp: function (e) {
                this.RepairAngle(
                    e.clientX - this._sideLeft,
                    this._mxRightWidth,
                    this._sideDown - e.clientY,
                    this._mxUpHeight
                );
                this.RepairTop();
                this.TurnLeft(this.LeftUp) || this.Scale || this.TurnDown(this.RightDown);
            },
            //左下
            LeftDown: function (e) {
                this.RepairAngle(
                    this._sideRight - e.clientX,
                    this._mxLeftWidth,
                    e.clientY - this._sideUp,
                    this._mxDownHeight
                );
                this.RepairLeft();
                this.TurnRight(this.RightDown) || this.Scale || this.TurnUp(this.LeftUp);
            },
            //左上
            LeftUp: function (e) {
                this.RepairAngle(
                    this._sideRight - e.clientX,
                    this._mxLeftWidth,
                    this._sideDown - e.clientY,
                    this._mxUpHeight
                );
                this.RepairTop();
                this.RepairLeft();
                this.TurnRight(this.RightUp) || this.Scale || this.TurnDown(this.LeftDown);
            },
            //修正程序
            //水平方向
            RepairX: function (iWidth, mxWidth) {
                iWidth = this.RepairWidth(iWidth, mxWidth);
                if (this.Scale) {
                    var iHeight = this.RepairScaleHeight(iWidth);
                    if (this.Max && iHeight > this._mxScaleHeight) {
                        iHeight = this._mxScaleHeight;
                        iWidth = this.RepairScaleWidth(iHeight);
                    } else if (this.Min && iHeight < this.minHeight) {
                        var tWidth = this.RepairScaleWidth(this.minHeight);
                        if (tWidth < mxWidth) {
                            iHeight = this.minHeight;
                            iWidth = tWidth;
                        }
                    }
                    this._styleHeight = iHeight;
                    this._styleTop = this._scaleTop - iHeight / 2;
                }
                this._styleWidth = iWidth;
            },
            //垂直方向
            RepairY: function (iHeight, mxHeight) {
                iHeight = this.RepairHeight(iHeight, mxHeight);
                if (this.Scale) {
                    var iWidth = this.RepairScaleWidth(iHeight);
                    if (this.Max && iWidth > this._mxScaleWidth) {
                        iWidth = this._mxScaleWidth;
                        iHeight = this.RepairScaleHeight(iWidth);
                    } else if (this.Min && iWidth < this.minWidth) {
                        var tHeight = this.RepairScaleHeight(this.minWidth);
                        if (tHeight < mxHeight) {
                            iWidth = this.minWidth;
                            iHeight = tHeight;
                        }
                    }
                    this._styleWidth = iWidth;
                    this._styleLeft = this._scaleLeft - iWidth / 2;
                }
                this._styleHeight = iHeight;
            },
            //对角方向
            RepairAngle: function (iWidth, mxWidth, iHeight, mxHeight) {
                iWidth = this.RepairWidth(iWidth, mxWidth);
                if (this.Scale) {
                    iHeight = this.RepairScaleHeight(iWidth);
                    if (this.Max && iHeight > mxHeight) {
                        iHeight = mxHeight;
                        iWidth = this.RepairScaleWidth(iHeight);
                    } else if (this.Min && iHeight < this.minHeight) {
                        var tWidth = this.RepairScaleWidth(this.minHeight);
                        if (tWidth < mxWidth) {
                            iHeight = this.minHeight;
                            iWidth = tWidth;
                        }
                    }
                } else {
                    iHeight = this.RepairHeight(iHeight, mxHeight);
                }
                this._styleWidth = iWidth;
                this._styleHeight = iHeight;
            },
            //top
            RepairTop: function () {
                this._styleTop = this._fixTop - this._styleHeight;
            },
            //left
            RepairLeft: function () {
                this._styleLeft = this._fixLeft - this._styleWidth;
            },
            //height
            RepairHeight: function (iHeight, mxHeight) {
                iHeight = Math.min(this.Max ? mxHeight : iHeight, iHeight);
                iHeight = Math.max(this.Min ? this.minHeight : iHeight, iHeight, 0);
                return iHeight;
            },
            //width
            RepairWidth: function (iWidth, mxWidth) {
                iWidth = Math.min(this.Max ? mxWidth : iWidth, iWidth);
                iWidth = Math.max(this.Min ? this.minWidth : iWidth, iWidth, 0);
                return iWidth;
            },
            //比例高度
            RepairScaleHeight: function (iWidth) {
                return Math.max(
                    Math.round((iWidth + this._borderX) / this.Ratio - this._borderY),
                    0
                );
            },
            //比例宽度
            RepairScaleWidth: function (iHeight) {
                return Math.max(
                    Math.round((iHeight + this._borderY) * this.Ratio - this._borderX),
                    0
                );
            },
            //转向程序
            //转右
            TurnRight: function (fun) {
                if (!(this.Min || this._styleWidth)) {
                    this._fun = fun;
                    this._sideLeft = this._sideRight;
                    this.Max && this._mxSet();
                    return true;
                }
            },
            //转左
            TurnLeft: function (fun) {
                if (!(this.Min || this._styleWidth)) {
                    this._fun = fun;
                    this._sideRight = this._sideLeft;
                    this._fixLeft = this._styleLeft;
                    this.Max && this._mxSet();
                    return true;
                }
            },
            //转上
            TurnUp: function (fun) {
                if (!(this.Min || this._styleHeight)) {
                    this._fun = fun;
                    this._sideDown = this._sideUp;
                    this._fixTop = this._styleTop;
                    this.Max && this._mxSet();
                    return true;
                }
            },
            //转下
            TurnDown: function (fun) {
                if (!(this.Min || this._styleHeight)) {
                    this._fun = fun;
                    this._sideUp = this._sideDown;
                    this.Max && this._mxSet();
                    return true;
                }
            },
            //停止缩放
            Stop: function () {
                removeEventHandler(document, "mousemove", this._fR);
                removeEventHandler(document, "mouseup", this._fS);
                if (isIE) {
                    removeEventHandler(this._obj, "losecapture", this._fS);
                    this._obj.releaseCapture();
                } else {
                    removeEventHandler(window, "blur", this._fS);
                }
            }
        };
//拖放程序
        var Drag = Class.create();
        Drag.prototype = {
            //拖放对象
            initialize: function (drag, options) {
                this.Drag = drag.get(0); //拖放对象
                this._x = this._y = 0; //记录鼠标相对拖放对象的位置
                this._marginLeft = this._marginTop = 0; //记录margin
                //事件对象(用于绑定移除事件)
                this._fM = BindAsEventListener(this, this.Move);
                this._fS = Bind(this, this.Stop);

                this.SetOptions(options);

                this.Limit = !!this.options.Limit;
                this.mxLeft = parseInt(this.options.mxLeft);
                this.mxRight = parseInt(this.options.mxRight);
                this.mxTop = parseInt(this.options.mxTop);
                this.mxBottom = parseInt(this.options.mxBottom);

                this.LockX = !!this.options.LockX;
                this.LockY = !!this.options.LockY;
                this.Lock = !!this.options.Lock;

                this.onStart = this.options.onStart;
                this.onMove = this.options.onMove;
                this.onStop = this.options.onStop;

                this._Handle = $(this.options.Handle).get(0) || this.Drag;
                this._mxContainer = $(this.options.mxContainer).get(0) || null;

                this.Drag.style.position = "absolute";
                //透明
                if (isIE && !!this.options.Transparent) {
                    //填充拖放对象
                    with (this._Handle.appendChild(document.createElement("div")).style) {
                        width = height = "100%";
                        backgroundColor = "#fff";
                        filter = "alpha(opacity:0)";
                        fontSize = 0;
                    }
                }
                //修正范围
                this.Repair();
                addEventHandler(
                    this._Handle,
                    "mousedown",
                    BindAsEventListener(this, this.Start)
                );
            },
            //设置默认属性
            SetOptions: function (options) {
                this.options = {
                    //默认值
                    Handle: "", //设置触发对象（不设置则使用拖放对象）
                    Limit: false, //是否设置范围限制(为true时下面参数有用,可以是负数)
                    mxLeft: 0, //左边限制
                    mxRight: 9999, //右边限制
                    mxTop: 0, //上边限制
                    mxBottom: 9999, //下边限制
                    mxContainer: "", //指定限制在容器内
                    LockX: false, //是否锁定水平方向拖放
                    LockY: false, //是否锁定垂直方向拖放
                    Lock: false, //是否锁定
                    Transparent: false, //是否透明
                    onStart: function () {
                    }, //开始移动时执行
                    onMove: function () {
                    }, //移动时执行
                    onStop: function () {
                    } //结束移动时执行
                };
                Extend(this.options, options || {});
            },
            //准备拖动
            Start: function (oEvent) {
                if (this.Lock) {
                    return;
                }
                this.Repair();
                //记录鼠标相对拖放对象的位置
                this._x = oEvent.clientX - this.Drag.offsetLeft;
                this._y = oEvent.clientY - this.Drag.offsetTop;
                //记录margin
                this._marginLeft = parseInt(CurrentStyle(this.Drag).marginLeft) || 0;
                this._marginTop = parseInt(CurrentStyle(this.Drag).marginTop) || 0;
                //mousemove时移动 mouseup时停止
                addEventHandler(document, "mousemove", this._fM);
                addEventHandler(document, "mouseup", this._fS);
                if (isIE) {
                    //焦点丢失
                    addEventHandler(this._Handle, "losecapture", this._fS);
                    //设置鼠标捕获
                    this._Handle.setCapture();
                } else {
                    //焦点丢失
                    addEventHandler(window, "blur", this._fS);
                    //阻止默认动作
                    oEvent.preventDefault();
                }
                //附加程序
                this.onStart();
            },
            //修正范围
            Repair: function () {
                if (this.Limit) {
                    //修正错误范围参数
                    this.mxRight = Math.max(
                        this.mxRight,
                        this.mxLeft + this.Drag.offsetWidth
                    );
                    this.mxBottom = Math.max(
                        this.mxBottom,
                        this.mxTop + this.Drag.offsetHeight
                    );
                    //如果有容器必须设置position为relative或absolute来相对或绝对定位，并在获取offset之前设置
                    !this._mxContainer ||
                    CurrentStyle(this._mxContainer).position == "relative" ||
                    CurrentStyle(this._mxContainer).position == "absolute" ||
                    (this._mxContainer.style.position = "relative");
                }
            },
            //拖动
            Move: function (oEvent) {
                //判断是否锁定
                if (this.Lock) {
                    this.Stop();
                    return;
                }
                //清除选择
                window.getSelection
                    ? window.getSelection().removeAllRanges()
                    : document.selection.empty();
                //设置移动参数
                var iLeft = oEvent.clientX - this._x,
                    iTop = oEvent.clientY - this._y;
                //设置范围限制
                if (this.Limit) {
                    //设置范围参数
                    var mxLeft = this.mxLeft,
                        mxRight = this.mxRight,
                        mxTop = this.mxTop,
                        mxBottom = this.mxBottom;
                    //如果设置了容器，再修正范围参数
                    if (!!this._mxContainer) {
                        mxLeft = Math.max(mxLeft, 0);
                        mxTop = Math.max(mxTop, 0);
                        mxRight = Math.min(mxRight, this._mxContainer.clientWidth);
                        mxBottom = Math.min(mxBottom, this._mxContainer.clientHeight);
                    }
                    //修正移动参数
                    iLeft = Math.max(
                        Math.min(iLeft, mxRight - this.Drag.offsetWidth),
                        mxLeft
                    );
                    iTop = Math.max(Math.min(iTop, mxBottom - this.Drag.offsetHeight), mxTop);
                }
                //设置位置，并修正margin
                if (!this.LockX) {
                    this.Drag.style.left = iLeft - this._marginLeft + "px";
                }
                if (!this.LockY) {
                    this.Drag.style.top = iTop - this._marginTop + "px";
                }
                //附加程序
                this.onMove();
            },
            //停止拖动
            Stop: function () {
                //移除事件
                removeEventHandler(document, "mousemove", this._fM);
                removeEventHandler(document, "mouseup", this._fS);
                if (isIE) {
                    removeEventHandler(this._Handle, "losecapture", this._fS);
                    this._Handle.releaseCapture();
                } else {
                    removeEventHandler(window, "blur", this._fS);
                }
                //附加程序
                this.onStop();
            }
        };
        // demo


        $(function () {
            var id = '{$id}';
            if (id) {
                $.ajax({
                    type: 'post',
                    url: '{$deliveryTemplateDetailUrl}',
                    async: false,
                    data: {
                        id: id
                    },
                    success: function (data) {
                        if (data.template_data) {
                            $('#template_name').val(data.template_name);
                            $('#input_width').val(data.template_data.width);
                            $('#input_height').val(data.template_data.height);
                            $('.reproduction').val(data.template_data.bg);
                            $('#container').css('backgroundImage', 'url(' + data.template_data.bg + ')');
                            $('#container').html($(tpl('tpl_drag', {items: data.template_data.items})));
                            $("#container").height(data.template_data.height + "mm").width(data.template_data.width + "mm");
                            $(".item-tip").hide();
                            $('.items').show();
                        }
                    }
                })
            } else {
                $("button[type=submit]").html('添加')
                $("#container").height("150mm").width("250mm");
            }


            $(".colorpicker").each(function () {
                var elm = this;
                utilAdmin.colorpicker(elm, function (color) {
                    $(elm).parent().prev().prev().val(color.toHexString());
                    $(elm).parent().prev().css("background-color", color.toHexString());
                    // $(elm).parent().prev().attr("data-color", color.toHexString());

                });
            });
            $(".colorclean").click(function () {
                $(this).parent().prev().prev().val("");
                $(this).parent().prev().css("background-color", "#FFF");
            });

            $('.drag').each(function () {
                bindEvents($(this));
            })

            $('.items .checkbox-inline').click(function (e) {
                if ($(e.target).find('input').length > 0) {
                    return;
                }
                if (currentDrag) {
                    var cate = currentDrag.attr("cate");
                    var values = [];
                    var titles = [];
                    var datas = [];
                    var vd = [];
                    $('.items').find(':checkbox:checked').each(function () {
                        var _titles = $(this).attr('title');
                        var _values = $(this).val();
                        var _vd = $(this).data('vd');
                        titles.push(_titles);
                        values.push(_values);
                        vd.push(_vd);
                        datas.push({
                            "value": _values,
                            "title": _titles,
                            "vd": _vd
                        });
                    });
                    if (cate == 1) {
                        currentDrag.attr('items', values.join(',')).attr('item-string', titles.join(',')).find('.text').text(
                            titles.join(','));
                    }
                    if (cate == 2) {
                        var _table = '';
                        _table += '<table border="1" style="width:100%">';
                        _table += '<tr style="font-weight:bold">';
                        $.each(datas, function (i, data) {
                            _table += '<td>&nbsp;' + data.title + '&nbsp;</td>';
                        });
                        _table += '</tr>';
                        for (i = 1; i < 5; i++) {
                            _table += '<tr>';
                            $.each(datas, function (ii, data) {
                                if (data.vd != '') {
                                    if (data.vd == 'number') {
                                        _table += '<td>' + i + '</td>';
                                    } else {
                                        _table += '<td>' + data.vd + i + '</td>';
                                    }
                                } else {
                                    _table += '<td>' + data.vd + '</td>';
                                }
                            });
                            _table += '</tr>';
                        }
                        _table += '<tr><td colspan="' + datas.length + '">提示: 以上表格数据为虚拟数据，打印时将替换为订单数据且打印时此行不会出现。</td></tr>';
                        _table += '</table>';
                        currentDrag.attr('items', values.join(',')).attr({
                            'item-string': titles.join(','),
                            'item-virtual': vd.join(',')
                        }).find('.text-table').html(_table);
                    }
                }
            });
            $('#item-font').change(function () {
                if (currentDrag) {
                    var cate = currentDrag.attr("cate");
                    var data = $(this).val();
                    currentDrag.attr('item-font', data);
                    if (data == '') {
                        data = "微软雅黑";
                    }
                    if (cate == 1) {
                        currentDrag.attr('item-font', data).find(".text").css('font-family', data);
                    }
                    if (cate == 2) {
                        currentDrag.attr('item-font', data).find(".text-table").css('font-family', data);
                    }
                }
            });
            $('#item-align').change(function () {
                if (currentDrag) {
                    var cate = currentDrag.attr("cate");
                    var data = $(this).val();
                    currentDrag.attr('item-align', data);
                    if (data == '') {
                        data = "left";
                    }
                    var str = data;
                    // if (data == 'align_left') {
                    //     str = "left";
                    // }
                    // if (data == 'align_middle') {
                    //     str = "center";
                    // }
                    // if (data == 'align_right') {
                    //     str = "right";
                    // }
                    if (cate == 1) {
                        currentDrag.attr('item-align', data).find(".text").css('text-align', str);
                    }
                    if (cate == 2) {
                        currentDrag.attr('item-align', data).find(".text-table").css('text-align', str);
                    }
                }
            });
            $('#item-size').change(function () {
                if (currentDrag) {
                    var cate = currentDrag.attr("cate");
                    var data = $(this).val();
                    currentDrag.attr('item-size', data);
                    if (data == '') {
                        data = 12;
                    }
                    if (cate == 1) {
                        currentDrag.find(".text").css('font-size', data + "pt");
                    }
                    if (cate == 2) {
                        currentDrag.find(".text-table").css('font-size', data + "pt");
                    }
                }
            });
            $('#item-bold').change(function () {
                if (currentDrag) {
                    var cate = currentDrag.attr("cate");
                    var data = $(this).val();
                    currentDrag.attr('item-bold', data);
                    if (cate == 1) {
                        if (data == 'bold') {
                            currentDrag.css('font-weight', 'bold');
                        } else {
                            currentDrag.find(".text").css('font-weight', 'normal');
                        }
                    }
                    if (cate == 2) {
                        if (data == 'bold') {
                            currentDrag.css('font-weight', 'bold');
                        } else {
                            currentDrag.find(".text-table").css('font-weight', 'normal');
                        }
                    }
                }
            });

            var flag = false;
            utilAdmin.validate($('.form-validate'), function (form) {
                if (flag) {
                    return false;
                }
                flag = true;
                var template_data = {};
                template_data.width = $('#input_width').val();
                template_data.height = $('#input_height').val();
                template_data.bg = $('#input_bg').val();
                template_data.items = [];
                $('.drag').each(function (k, v) {
                    var $this = $(this);
                    var item = {};

                    item.index = $this.attr('index')
                    item.cate = $this.attr('cate')
                    item.style = $this.attr('style')
                    item.fields = $this.attr('fields')
                    item.item_size = $this.attr('item-size')
                    item.item_font = $this.attr('item-font')
                    item.item_align = $this.attr('item-align')
                    item.item_color = $this.attr('item-color')
                    item.item_pre = $this.attr('item-pre')
                    item.item_last = $this.attr('item-last')
                    item.items = $this.attr('items')
                    item.item_string = $this.attr('item-string')
                    item.item_bold = $this.attr('item-bold')
                    item.from_top = $this.css('top').replace('px', '')
                    item.from_left = $this.css('left').replace('px', '')
                    item.width = $this.css('width').replace('px', '');
                    item.height = $this.css('height').replace('px', '')
                    if (item.item_string !== '' && item.item_string !== undefined) {
                        template_data.items.push(item);
                    }

                })
                // console.log(template_data)

                $.ajax({
                    type: 'post',
                    url: '{$saveDeliveryTemplateUrl}',
                    data: {
                        'delivery_template_id': '{$id}',
                        'template_name': $('#template_name').val(),
                        'template_data': template_data,
                    },
                    success: function (data) {
                        if (data.code > 0) {
                            utilAdmin.message('操作成功', 'success', "{:__URL('ADDONS_ADMIN_MAINformList')}");
                        } else {
                            utilAdmin.message(data.message, 'info');
                        }
                    }
                })
            })
        });

        var currentDrag = false;
        // 参照底图的图片空间
        $('body').on('click', '[data-toggle="editExpressPicture"]', function () {
            var _this = this;
            utilAdmin.pictureDialog(_this, false, function (content) {
                $('.reproduction').val(content.path[0]);
                $('#container').css('backgroundImage', 'url(' + content.path[0] + ')');
            })
        });
        //参照底图清除
        $('.clearPic').on('click', function () {
            $('.reproduction').val('');
            $('#container').css('backgroundImage', 'url()');
        })

        // 点击编辑内容框
        function addInput(n) {
            var index = $('#container .drag').length + 1;
            if (n == 1) {
                var data = '<div class="drag" cate="2" style="width: auto; height: auto; padding: 10px;" index="' + index +
                    '" style="z-index:' + index + '" fields="" item-size="12" item-font="微软雅黑" item-align="left">';
                data += '<div class="text-table">';
                data += '请在左侧先选择列';
                data += '</div>';
                data +=
                    '<div class="rRightDown"> </div><div class="rLeftDown"> </div><div class="rRightUp"> </div><div class="rLeftUp"> </div><div class="rRight"> </div><div class="rLeft"> </div><div class="rUp"> </div><div class="rDown"></div>';
                data += '</div>';
                var drag = $(data)
            } else {
                var drag = $('<div class="drag" cate="1" index="' + index + '" style="z-index:' + index +
                    '" fields="" item-size="12" item-font="微软雅黑" item-align="left" item-color="#000"><div class="text" style="font-size:12pt"></div><div class="rRightDown"> </div><div class="rLeftDown"> </div><div class="rRightUp"> </div><div class="rLeftUp"> </div><div class="rRight"> </div><div class="rLeft"> </div><div class="rUp"> </div><div class="rDown"></div></div>'
                );
            }
            $('#container').append(drag);
            bindEvents(drag);
            setCurrentDrag(drag);
        }

        // 删除打印项
        function delInput() {
            var _index = currentDrag.attr("index");
            $(".drag").each(function () {
                var index = $(this).attr("index");
                if (index == _index) {
                    $(this).remove();
                }
            });
            $(".deleteinput").hide();
        }

        // 单据宽高的修改
        function pagesize() {
            var _width = $("input[name=width]").val();
            var _height = $("input[name=height]").val();
            if (_width < 10) {
                utilAdmin.message("最低宽度不小于10", "danger");
                $("input[name=width]").val("10");
                return;
            }
            if (_width > 400) {
                utilAdmin.message("最大宽度不大于400", "danger");
                $("input[name=width]").val("400");
                return;
            }
            $("#container").height(_height + "mm").width(_width + "mm");
        }

        function bindEvents(obj) {
            var index = obj.attr('index');
            var rs = new Resize(obj, {
                Max: true,
                mxContainer: "#container"
            });
            rs.Set($(".rRightDown", obj), "right-down");
            rs.Set($(".rLeftDown", obj), "left-down");
            rs.Set($(".rRightUp", obj), "right-up");
            rs.Set($(".rLeftUp", obj), "left-up");
            rs.Set($(".rRight", obj), "right");
            rs.Set($(".rLeft", obj), "left");
            rs.Set($(".rUp", obj), "up");
            rs.Set($(".rDown", obj), "down");
            new Drag(obj, {
                Limit: true,
                mxContainer: "#container"
            });
            $('.drag .remove').unbind('click').click(function () {
                $(this).parent().remove();
            });

            $.contextMenu({
                selector: '.drag[index=' + index + ']',
                callback: function (key, options) {
                    var index = $(this).attr('index');
                    if (key == 'next') {
                        var nextdiv = $(this).next('.drag');
                        if (nextdiv.length > 0) {
                            nextdiv.insertBefore($(this));
                        }
                    } else if (key == 'prev') {
                        var prevdiv = $(this).prev('.drag');
                        if (prevdiv.length > 0) {
                            $(this).insertBefore(prevdiv);
                        }
                    } else if (key == 'last') {
                        var len = $('.drag').length;
                        if (index >= len - 1) {
                            return;
                        }
                        var last = $('#container .drag:last');
                        if (last.length > 0) {
                            $(this).insertAfter(last);
                        }
                    } else if (key == 'first') {
                        var index = $(this).index();
                        if (index <= 1) {
                            return;
                        }
                        var first = $('#container .drag:first');
                        if (first.length > 0) {
                            $(this).insertBefore(first);
                        }
                    } else if (key == 'delete') {
                        $(this).remove();
                        $('.items').hide();
                        $(".item-tip").show();
                        $(".deleteinput").hide();
                    }
                    var n = 1;
                    $('.drag').each(function () {
                        $(this).css("z-index", n);
                        n++;
                    })
                },
                items: {
                    "next": {
                        name: "调整到上层"
                    },
                    "prev": {
                        name: "调整到下层"
                    },
                    "last": {
                        name: "调整到最顶层"
                    },
                    "first": {
                        name: "调整到最低层"
                    },
                    "delete": {
                        name: "删除元素"
                    }
                }
            });
            obj.unbind('mousedown').mousedown(function () {
                setCurrentDrag(obj);
            });
        }

        $('body').on('click', '.editContent', function () {
            addInput();
        })
        $('body').on('click', '.deleteinput', function () {
            delInput();
        })
        $('body').on('change', '.documentsWidth', function () {
            pagesize();
        });
        $('body').on('change', '.documentsHeight', function () {
            pagesize();
        });

    })
</script>